import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { promptAction } from '@kit.ArkUI';

let GENERATION_URL =
  "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" // GENERATION_URL="http://192.168.227.230:5000/post-endpoint"
let TAG = "_:_VLM"

export default class VLMmanager {
  private requestOptions: http.HttpRequestOptions = {}

  InitParam(urlstr: string, prompt: string) {

    this.requestOptions = {
      method: http.RequestMethod.POST,
      header: {
        'Authorization': 'Bearer sk-11ffe74a9d494bc3bb2d5ca3b27eedbd',
        // 'Content-Type': 'application/json'
      },
      extraData: JSON.stringify({
        "model": "qwen-vl-max-latest",
        "messages": [
          {
            "role": "user",
            "content": [
              {
                "type": "text", "text": prompt
              },
              {
                "type": "image_url",
                "image_url": {
                  "url": urlstr
                },
              }
            ],
          }
        ]
      })
    }
  }

  parseVLMResult(result): string {
    let TAG = "_:[parseResultVLM]"
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result, "duration": 5000
      })
    }
    try {
      let resultj = JSON.parse(result)
      console.log(TAG, "parse success ", resultj["choices"][0]["message"]["content"], "<=", JSON.stringify(resultj))
      return resultj["choices"][0]["message"]["content"].replace(/\n/g, "")
    } catch (e) {
      console.error(TAG, "parseResult", e)
      return result
    }
  }

  async VLM(imgstr: string, prompt: string, fromBase64: boolean = true): Promise<string> {
    if (fromBase64) {
      this.InitParam("data:image/jpeg;base64," + imgstr, prompt)
    } else {
      this.InitParam(imgstr, prompt)
    }
    return await httpService.requestMain(GENERATION_URL, this.requestOptions, (response) => {
      return this.parseVLMResult(response)
    })
  }
}


// payload = {
//   "model": "qwen-vl-max-latest",
//   "messages": [
//     {
//       "role": "user",
//       "content": [
//         {
//           "type": "image_url",
//           "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" },
//         },
//         { "type": "text", "text": "这是什么" },
//       ],
//     }
//   ],
// }
// response = requests.post(
//   "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
//   headers = headers,
//   json = payload,
// )
// print(response.json()["choices"][0]["message"]["content"])